<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<input type="text" id="inputValue"/>
<button id="btn">打开/创建database</button>
<button id="getBtn">获取</button>
<script>
  // 我们的客户数据看起来像这样。
  const customerData = [
    {ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com"},
    {ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org"},
    {ssn: "666-66-6666", name: "Tony", age: 23, email: "ony@home.org"}
  ];
  let db = null
  const openDatabase = function (version) {
    console.log('database version:', version)
    const request = window.indexedDB.open('MyThreeDatabase', version)

    request.onsuccess = function (event) {
      db = event.target.result
      console.log('database success')
    }

    request.onerror = function (event) {
      console.log('database fail:', event.target.error.message)
    }

    request.onupgradeneeded = function (event) {
      console.log('database onupgradeneeded')

      // 保存 IDBDataBase 接口
      db = event.target.result
      // 设置 autoIncrement 标志为 true 来创建一个名为 customers 的对象仓库
      // 使用键生成器，当你向对象仓库新增记录时键会自动生成。对象仓库生成的键往往从 1 开始，然后自动生成的新的键会在之前的键的基础上加 1。
      const objectStore = db.createObjectStore('customers', {autoIncrement: true})
      console.log('database result', db, objectStore)

      // 因为 customers 对象仓库拥有键生成器，所以它的键会自动生成。
      // 被插入的数据可以表示如下：
      // key : 1 => value : "xxx"
      // key : 2 => value : "xxx"
      customerData.forEach(item => {
        objectStore.add(item)
      })
    }
  }
  btn.addEventListener('click', () => {
    openDatabase(Number(inputValue.value || 1))
  })

  getBtn.addEventListener('click', () => {
    const transaction = db.transaction('customers')
    const objectStore = transaction.objectStore('customers')
    const request = objectStore.get(1)
    request.onsuccess = function (event) {
      console.log('get ssn 444-44-4444:', event.target,request.result)
    }
  })
</script>
</body>
</html>
